/**
 * Created by John on 2016/7/1.
 */
var microblog = require('./microblog');
module.exports = User;

function User(user) {
    this.name = user.name;
    this.password = user.password;
}

User.prototype.save = function (callback) {
    var user = {
        name: this.name,
        password: this.password
    };

    microblog.connect(connect);

    function connect(db) {
        db.collection('users', createUsers);
    }

    function createUsers(err, collection) {
        microblog.error(err, callback);
        collection.ensureIndex('name', {unique: true});
        collection.save(user, saveUser);
    }

    function saveUser(err, item) {
        microblog.error(err, callback);
        callback(err, item);
    }
};

User.prototype.get = function (callback) {
    microblog.connect(connect);
    var name = this.name;

    function connect(db) {
        db.collection('users', findOneUser);
    }

    function findOneUser(err, collection) {
        microblog.error(err, callback);
        var curros= collection.findOne({name: name});
        curros.error(err, callback);
        if (item) {
            var user = new User(item);
            callback(err, user);
        } else {
            callback(err, null);
        }
    }

    function sendUser(err, item) {
        microblog.error(err, callback);
        if (item) {
            var user = new User(item);
            callback(err, user);
        } else {
            callback(err, null);
        }
    }
};